<?php
namespace Dealer\Model;
use Think\Model;
/**
 *
 */
class IndexModel extends Model{

    protected $tableName = 'public_single_supplier';
    /**
     * 待审核产品列表
     */
    public function auditProductList(){
        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');

         //酒店供应商待审核的产品列表
        $hotelList=M('public_single_room_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_ROOM__ as r on r.room_id=p.room_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.room_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.star_level,r.room_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_supplier_id'=>$admin_id,'p.is_review'=>-1))
            ->order('p.room_priceId desc')
            ->limit(10)
            ->select();
        //保险供应商
        $insureList=M('public_single_insure_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_INSURE__ as r on r.insure_id=p.insure_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.insure_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.insure_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_supplier_id'=>$admin_id,'p.is_review'=>-1))
            ->order('p.insure_priceId desc')
            ->limit(10)
            ->select();
        //景区供应商
        $scenicList=M('public_single_scenic_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_SCENIC__ as r on r.scenic_id=p.scenic_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.scenic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.scenic_name,r.scenic_level,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_supplier_id'=>$admin_id,'p.is_review'=>-1))
            ->order('p.scenic_priceId desc')
            ->limit(10)
            ->select();
        //交通供应商
        $trafficList=M('public_single_traffic_price as p')
            ->join("LEFT JOIN __PUBLIC_SINGLE_TRAFFIC__ as r on r.traffic_id=p.traffic_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id=p.supplier_id")
            ->join("LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as a on a.supplier_id=p.audit_id")
            ->field('s.supplier_sn,p.supplier_id,r.traffic_id,p.adult_actual_cost,p.child_actual_cost,p.entry_id,p.product_sn,r.traffic_name,s.supplier_name,s.type,s.start_time,s.end_time,p.is_review,p.is_shelves,a.supplier_name as audit_name')
            ->where(array('s.admin_supplier_id'=>$admin_id,'p.is_review'=>-1))
            ->order('p.traffic_priceId desc')
            ->limit(10)
            ->select();

        return ['hotelList'=>$hotelList,'insureList'=>$insureList,'scenicList'=>$scenicList,'trafficList'=>$trafficList];

    }


    /**
     * 最新消息列表
     */
    public function messList(){
       $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
       $list= M('line_operator as lo')
           ->join('LEFT JOIN __PUBLIC_LINE__ as sl on sl.line_id=lo.line_id')
           ->join('LEFT JOIN __OPERATOR__ as o on o.operator_id=lo.operator_id')
           ->join('LEFT JOIN __OPERATOR_LINE_SUPPLIER__ as su on sl.supplier_id=su.supplier_id')
           ->field('o.operator_name,sl.line_name,sl.guests_num,sl.start_time,sl.end_time,sl.line_sn,sl.child_money,sl.oldman_money,sl.adult_money,lo.partner_time,su.supplier_name,lo.partner_status')
           ->where(['sl.supplier_id'=>$admin_id])
           ->order('lo.partner_time desc')
           ->limit(10)
           ->select();

       return $list;

    }

    /**
     * 最新订单列表
     */
    public  function orderList(){

        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
        $where['origin_line_supplier_id']=$admin_id;
        $where['o.order_status']=3;
        $field="o.order_id,o.adult_num,o.child_num,o.oldMan_num,o.order_num,l.line_name,l.group_num,g.expect_num,l.line_sn,o.create_time,g.group_time,g.out_time,g.group_status";
        $list=M('line_orders as o')
            ->join(" __PUBLIC_LINE__ as l on o.line_id=l.line_id")
            ->join("__PUBLIC_GROUP__ as g on o.group_id=g.group_id")
            ->field($field)
            ->limit(10)
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        return $list;
    }


    public function getSupplierOrderTotalMoney($order_id){
        $orderInfo=M('line_orders')->where(array('order_id'=>$order_id))->find();
        $lineInfo=M('public_line')->where(array('line_id'=>$orderInfo['line_id']))->find();


    }



    /**
     * 按天的饼状营业额
     */
    public function turnover($day){

        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
        //当天的订单ID
        $allOrder=M('line_orders as o')
            ->field('o.order_id,o.adult_num,o.child_num,o.oldMan_num,l.adult_money,l.child_money,l.oldman_money,l.origin_line_id,g.closing_total_money')
            ->join("__PUBLIC_LINE__ as l on l.line_id=o.line_id")
            ->join("__PUBLIC_GROUP__ as g on g.group_id=o.group_id")
            //array('egt',1)
            ->where(['o.origin_line_supplier_id'=>$admin_id,'o.order_status'=>3,'_string'=>"DATE(FROM_UNIXTIME(g.closing_time))=DATE('{$day}')",'g.closing_total_money'=>array('gt',0)])
            ->select();
        $all_order_id=[];
        $totalMoney=0;
        $costMoney=0;
        foreach ($allOrder as $k=>$v){
            $totalMoney+=$v['closing_total_money'];
            $all_order_id[]=$v['order_id'];
        }
        if($all_order_id){
            $costMoney=M('order_unit_detail')->where(array('order_id'=>array('in',implode(',',$all_order_id)),'is_compose'=>0))->sum('unit_cost');
        }
        $profit=$totalMoney-$costMoney;
        $profitPercent=sprintf('%.1f',$profit/$totalMoney*100);
        $totalPercent=100-$profitPercent;
        return['total'=>$totalMoney,'profit'=>$profit,'cost'=>$costMoney,'profitPercent'=>$profitPercent,'totalPercent'=>$totalPercent,'orderCount'=>count($allOrder)];
    }



    /**
     * 按天的饼状营业额
     */
    public function _turnover($day){

        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
        //当天的订单ID
        $allOrder=M('line_orders as o')
            ->field('o.order_id,o.adult_num,o.child_num,o.oldMan_num,l.adult_money,l.child_money,l.oldman_money,l.origin_line_id,g.closing_total_money')
            ->join("__PUBLIC_LINE__ as l on l.line_id=o.line_id")
            ->join("__PUBLIC_GROUP__ as g on g.group_id=o.group_id")
            ->where(['o.origin_line_supplier_id'=>$admin_id,'o.order_status'=>array('egt',1),'_string'=>"DATE(FROM_UNIXTIME(g.closing_time))=DATE('{$day}')",'g.closing_total_money'=>array('gt',0)])
            ->select();
        //模型
        $order_unit_detail_DB=M('order_unit_detail');
        //供应商总额:给运营商的线路价格+酒店升级+交通升级+保险+补房差
        $all_order_id=[];
        $base_cost=0;//基础成本
        $room_diff=0;//给运营商补房差
        $hotel_money=0;//给运营商酒店升级费用
        $insure_money=0;//给运营商保险升级费用
        $traffic_money=0;//给运营商交通升级费用
        $operator_cost=0;//运营商线路总成本;

        foreach ($allOrder as $k=>$v){
            $all_order_id[]=$v['order_id'];
            $base_cost+=$v['adult_num']*$v['adult_money']+$v['child_num']*$v['child_money'];
            //所有产品
            $unitAll=$order_unit_detail_DB->where(array('order_id'=>$v['order_id'],'is_compose'=>0))->select();
            foreach ($unitAll as $kk=>$vv){
                //给供应商的补房差
                if($vv['room_diff']){
                    $room_diff+=$vv['room_diff_cost'];
                }
                //给运营商的 升级费用 类型 1交通,2酒店,3景区,4保险
                if($vv['is_upgrade']==1){
                    //酒店
                    if($vv['source_type']==2){
                        //$hotel_money+=$vv['room_count']*$vv['upgrade_adult_price'];
                        $hotel_money+=$vv['room_to_operator_price'];
                    }else{
                        //交通
                        if($vv['source_type']==1){
                            $traffic_money+=$vv['adult_count']*$vv['upgrade_adult_price']+$vv['child_count']*$vv['upgrade_child_price']+$vv['old_man_count']*$vv['upgrade_adult_price'];
                        }

                    }
                }else{
                    //保险
                    if($vv['source_type']==4){
                        $insure_money+=$vv['adult_count']*$vv['upgrade_adult_price']+$vv['child_count']*$vv['upgrade_child_price']+$vv['old_man_count']*$vv['upgrade_adult_price'];
                    }
                }
            }

            //运营商使用到的所有单品总成本
            $operator_cost+=$order_unit_detail_DB->where(array('order_id'=>$v['order_id'],'is_compose'=>1))->sum('unit_cost');
        }

        //总金额  运营商成本(供应商提供产品部分)
        $totalMoney=$base_cost+$hotel_money+$insure_money+$traffic_money;


        //供应商总成本
        //$costMoney=$hotel_cost+$insure_cost+$traffic_cost+$scenic_cost;
        //供应商所有使用到的单品供应商的商品总价
        if($all_order_id){
            $costMoney=M('order_unit_detail')->where(array('order_id'=>array('in',implode(',',$all_order_id)),'is_compose'=>0))->sum('unit_cost');
        }


        $profit=$totalMoney-$costMoney;

        $profitPercent=sprintf('%.1f',$profit/$totalMoney*100);

        $totalPercent=100-$profitPercent;
        return['total'=>$totalMoney,'cost'=>$costMoney,'profitPercent'=>$profitPercent,'totalPercent'=>$totalPercent,'orderCount'=>count($allOrder)];
    }
    /**
     * 可选 的年份
     */
    public function yearList(){
        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
        $list=M('line_orders')->field("FROM_UNIXTIME(create_time,'%Y') as y")
            ->where(['origin_line_supplier_id'=>$admin_id,'order_status'=>array('egt',1)])->group('y')->select();
        if(empty($list)){
            $list[0]['year']=date('Y');
        }
        return $list;
    }

    /**
     * 报表
     */
    public function report(){
        $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
        //type 1年 2月
        $type=I('type',1,'intval');
        $year=I('year',date('Y'),'intval');
        $month=I('month',1,'intval');

        $db_prefix=C('DB_PREFIX');

        if($type==1){
            //按年分12个月展示
            $where['cd.supplier_id']=$admin_id;
            $where['g.closing_total_money']=array('gt',0);
            $where['_string']="FROM_UNIXTIME(g.closing_time,'%Y')={$year}";
            $list=M('order_cost_detail as cd')
                ->join("__PUBLIC_GROUP__ as g on g.group_id=cd.group_id")
                ->field("cd.*,g.out_time,(select count({$db_prefix}line_orders.order_id) from {$db_prefix}line_orders where {$db_prefix}line_orders.group_id=cd.group_id and {$db_prefix}line_orders.order_status=3 ) as orderCount ")
                ->where($where)
                ->select();

            $moneyList=array(
                '1'=>array('name'=>'一月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '2'=>array('name'=>'二月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '3'=>array('name'=>'三月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '4'=>array('name'=>'四月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '5'=>array('name'=>'五月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '6'=>array('name'=>'六月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '7'=>array('name'=>'七月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '8'=>array('name'=>'八月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '9'=>array('name'=>'九月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '10'=>array('name'=>'十月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '11'=>array('name'=>'十一月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
                '12'=>array('name'=>'十二月','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0),
            );
            foreach ($list as $k=>$v){
                $month=date('m',$v['closing_time']);
                foreach ($moneyList as $mk=>$mv){
                    //相应月份数据相加
                    if($month==$mk){
                        $moneyList[$mk]['orderNum']+=$v['orderCount'];
                        $moneyList[$mk]['turnover']+=$v['actually_money'];//供应商实际结算金额
                        $moneyList[$mk]['cost']+=$v['supplier_unit_cost_total'];//所有单品的总成本
                    }
                }
            }

            foreach ($moneyList as $k=>$v){
                $moneyList[$k]['profit']=$v['turnover']-$v['cost'];
            }
            return $moneyList;

        }else{
            //按月,按天来算
            $dayCount=cal_days_in_month(CAL_GREGORIAN,$month,date('Y'));
            $dayList=[];
            for($i=1;$i<=$dayCount;$i++){
                $dayList[$i]=array('name'=>$i.'号','orderNum'=>0,'profit'=>0,'turnover'=>0,'cost'=>0);
            }

            foreach ($dayList as $mk=>$mv){
                $tempDay=date("Y-m-d",strtotime(date('Y-'.$month,time())."-".$mk));
                $turnover=self::turnover($tempDay);
                $dayList[$mk]['orderNum']=$turnover['orderCount'];
                $dayList[$mk]['turnover']=$turnover['total'];
                $dayList[$mk]['cost']=$turnover['cost'];
            }
            foreach ($dayList as $k=>$v){
                $dayList[$k]['profit']=$v['turnover']-$v['cost'];
            }
            return $dayList;
        }

    }


}
